package cn.y.operation.framework.utils.send;

import cn.y.operation.framework.utils.dev.DateUtils;
import cn.y.operation.framework.utils.dev.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @ClassName: EmailUtils
 * @author: 叶子豪
 * @create: 2021-04-22 14:12
 */
@Component
public class EmailUtils {

    private static final Logger logger = LoggerFactory.getLogger(EmailUtils.class);

    static JavaMailSender javaMailSender;
    private static TemplateEngine templateEngine;

    @Resource
    public void setJavaMailSender(JavaMailSender javaMailSender) {
        EmailUtils.javaMailSender = javaMailSender;
    }

    @Resource
    public void setTemplateEngine(TemplateEngine templateEngine) {
        EmailUtils.templateEngine = templateEngine;
    }

    public static void sendSimpleMail() throws MessagingException {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("这是一封测试邮件");
        message.setFrom("sz.yzh@jovision.com");
        message.setTo("1715309770@qq.com");
        message.setCc("37xxxxx37@qq.com");
        message.setBcc("14xxxxx098@qq.com");
        message.setSentDate(DateUtils.getFormatDate());
        message.setText("这是测试邮件的正文");
        javaMailSender.send(message);
    }

    public static void sendThymeleafMail() {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setSubject("这是一封测试邮件");
            helper.setFrom("sz.yzh@jovision.com");
            helper.setTo("1715309770@qq.com");
            helper.setCc("37xxxxx37@qq.com");
            helper.setBcc("14xxxxx098@qq.com");
            helper.setSentDate(DateUtils.getFormatDate());

            Context context = new Context();
            context.setVariable("username", "yyy");
            context.setVariable("num", StringUtils.random(10, false, true));
            context.setVariable("verificationCode", StringUtils.random(5));
            String process = templateEngine.process("module/mail.html", context);
            helper.setText(process, true);
        } catch (MessagingException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        javaMailSender.send(mimeMessage);
    }

}
